package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberEntityVo;
import com.atguigu.gulimall.auth.feignService.MemberFeignService;
import com.atguigu.gulimall.auth.feignService.ThirdPartyService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Slf4j
@Controller
public class LoginController {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ThirdPartyService thirdPartyService;
    @Autowired
    MemberFeignService memberFeignService;
    /**
     * 登录功能
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        R login = memberFeignService.login(vo);
        if (login.getCode()==0){
            log.info("登录成功");
            MemberEntityVo data = login.getData("data", new TypeReference<MemberEntityVo>() {});
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://mall.com";
        }else {
            HashMap<String, String> errorMap = new HashMap<>();
            errorMap.put("msg",login.getData("msg", new TypeReference<String>() {}));
            redirectAttributes.addFlashAttribute("errors",errorMap);
            return "redirect:http://auth.mall.com/login.html";
        }
    }
    /**
     * 跳转登录页面
     */
    @GetMapping("/login.html")
    public String toLogin(HttpSession session){
        MemberEntityVo memberEntityVo = (MemberEntityVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberEntityVo!=null){
            return "redirect:http://mall.com";
        }else {
            return "login";
        }

    }

    /**
     * 获取短信验证码
     * @param phone
     * @return
     */
    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){
        String token = redisTemplate.opsForValue().get("phone");

        //TODO 接口防刷
        if (token!= null){
            String[] s = token.split("_");
            long time = Long.parseLong(s[1]);
            //60秒内禁止重试获取验证码
            if (time<600000){
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        if (token!=null){
            return R.error("验证码已存在");
        }else {
            String code = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
            redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CATCH_PREFIX+phone,code,5, TimeUnit.MINUTES);
            thirdPartyService.sendCodeMessage(phone,code.substring(0,5));
            System.out.println("发送的验证码是"+code.substring(0,5));
            return R.ok();
        }

    }
    /**
     * 注册功能
     */
    @PostMapping("/register")
    public String regist(@Valid UserRegistVo vo , BindingResult result, Model model){
        if (result.hasErrors()){
            HashMap<String, String> errorMap = new HashMap<>();
            for (FieldError fieldError : result.getFieldErrors()) {
                errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            model.addAttribute("errors",errorMap);
            return "redirect:http://auth.mall.com/reg.html";
        }

        String phone = AuthServerConstant.SMS_CODE_CATCH_PREFIX+vo.getPhone();
        String token = redisTemplate.opsForValue().get(phone);
        //获取验证码
        String[] codeMsg = token.split("_");

        if (token!=null&&codeMsg[0].equals(vo.getCode())){
            //验证码对比成功
            //删除验证码
            redisTemplate.delete(phone);
            //远程调用会员服务，进行注册
            R r = memberFeignService.registMember(vo);
            if (r.getCode()==0){
                return "redirect:http://auth.mall.com/login.html";
            }else {
                HashMap<String, String> errorMap = new HashMap<>();
                errorMap.put("msg",r.getData("msg",new TypeReference<String>(){}));
                model.addAttribute("errors",errorMap);
                return "redirect:http://auth.mall.com/reg.html";
            }

        }else {
            HashMap<String, String> errorMap = new HashMap<>();
            errorMap.put("code","验证码错误");
            model.addAttribute("errors",errorMap);
            return "redirect:http://auth.mall.com/reg.html";
        }

    }
}
